<template>
  <div class="min-h-screen bg-gray-50">


    <!-- 主要内容区域 -->
    <div class="container mx-auto px-8 py-8 pt-28">
      <!-- 页面标题和操作按钮 -->
      <div class="flex justify-between items-start mb-8">
        <div>
          <h1 class="text-3xl font-bold text-gray-900 mb-2">我的课程</h1>
          <p class="text-gray-600">统一查看我的班级、我购买的课程与我观看的课程</p>
        </div>
        <div class="flex gap-4">
          <el-button 
            type="primary" 
            size="large" 
            class="flex items-center gap-2"
            @click="showJoinDialog = true"
          >
            <el-icon><Plus /></el-icon>
            加入班级
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">已加入班级</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.joinedClasses }}</p>
            </div>
            <div class="p-3 bg-blue-100 rounded-full">
              <el-icon class="text-blue-600 text-xl"><School /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">我购买的课程</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.purchasedCourses }}</p>
            </div>
            <div class="p-3 bg-yellow-100 rounded-full">
              <el-icon class="text-yellow-600 text-xl"><Clock /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">我关注的</p>
              <p class="text-2xl font-bold text-gray-900">{{ stats.followedItems }}</p>
            </div>
            <div class="p-3 bg-green-100 rounded-full">
              <el-icon class="text-green-600 text-xl"><Reading /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 模块一：我的班级 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">我的班级</h3>
        </div>
        
        <div v-if="loading" class="p-8 text-center">
          <el-icon class="text-4xl text-gray-400 mb-4"><Loading /></el-icon>
          <p class="text-gray-500">加载中...</p>
        </div>
        
        <div v-else-if="myClasses.length === 0" class="p-8 text-center">
          <el-icon class="text-4xl text-gray-400 mb-4"><School /></el-icon>
          <p class="text-gray-500 mb-4">您还没有加入任何班级</p>
          <el-button type="primary" @click="showJoinDialog = true">立即加入班级</el-button>
        </div>
        
        <div v-else class="divide-y divide-gray-200">
          <div 
            v-for="classItem in myClasses" 
            :key="classItem.id" 
            class="p-6 hover:bg-gray-50 transition-colors"
          >
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-4">
                <div class="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center shadow-md">
                  <span class="text-white text-2xl font-bold select-none leading-none">{{ getFirstChar(classItem.className) }}</span>
                </div>
                <div>
                  <div class="flex items-center gap-3 mb-2">
                    <h4 class="text-lg font-medium text-gray-900">{{ classItem.className }}</h4>
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {{ classItem.classCode }}
                    </span>
                  </div>
                  <div class="flex items-center gap-6 text-sm text-gray-600">
                    <span>年级：{{ classItem.grade }}</span>
                    <span>班主任：{{ classItem.teacherName }}</span>
                    <span>学生：{{ classItem.studentCount }}人</span>
                    <span>加入时间：{{ formatDate(classItem.joinDate) }}</span>
                  </div>
                </div>
              </div>
              <div class="flex items-center gap-3">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewClassDetail(classItem)"
                >
                  查看详情
                </el-button>
                <el-button 
                  type="warning" 
                  size="small" 
                  @click="leaveClass(classItem)"
                >
                  退出班级
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 模块二：我购买的课程 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">我购买的课程</h3>
        </div>
        <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div v-for="course in purchasedList" :key="course.id" class="p-5 rounded-lg border hover:shadow-sm transition">
            <div class="text-sm text-gray-500 mb-1">系列课</div>
            <div class="font-semibold text-gray-900 mb-2">{{ course.title }}</div>
            <div class="text-sm text-gray-600 mb-3">进度：{{ course.progress }}%</div>
            <div class="flex items-center justify-between">
              <span class="text-xs text-gray-500">购买于 {{ formatDate(course.buyAt) }}</span>
              <el-button size="small" @click="goToSeries(course)">继续学习</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 模块三：我关注的班级/课程 -->
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">我关注的班级 / 课程</h3>
        </div>
        <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div v-for="item in followedList" :key="item.id" class="p-5 rounded-lg border hover:shadow-sm transition">
            <div class="text-sm text-gray-500 mb-1">{{ item.type === 'class' ? '直播班级' : '系列课' }}</div>
            <div class="font-semibold text-gray-900 mb-2">{{ item.title }}</div>
            <div class="text-sm text-gray-600 mb-3">关注于：{{ formatDate(item.followAt) }}</div>
            <div class="flex items-center justify-between">
              <span class="text-xs text-gray-500">{{ item.type === 'class' ? '开班：' + item.dateRange : '进度 ' + item.progress + '%' }}</span>
              <el-button size="small" @click="goToFollowed(item)">{{ item.type === 'class' ? '查看班级' : '查看课程' }}</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 申请记录 -->
      <div v-if="applications.length > 0" class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">申请记录</h3>
        </div>
        
        <div class="divide-y divide-gray-200">
          <div 
            v-for="application in applications" 
            :key="application.id" 
            class="p-6"
          >
            <div class="flex items-center justify-between">
              <div>
                <div class="flex items-center gap-3 mb-2">
                  <h4 class="font-medium text-gray-900">{{ application.className }}</h4>
                  <span 
                    :class="getApplicationStatusClass(application.status)"
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  >
                    {{ getApplicationStatusText(application.status) }}
                  </span>
                </div>
                <p class="text-sm text-gray-600 mb-2">
                  申请时间：{{ formatDate(application.applyDate) }}
                </p>
                <p v-if="application.reason" class="text-sm text-gray-700">
                  申请理由：{{ application.reason }}
                </p>
                <p v-if="application.rejectReason" class="text-sm text-red-600 mt-1">
                  拒绝原因：{{ application.rejectReason }}
                </p>
              </div>
              <div class="flex items-center gap-2">
                <el-button 
                  v-if="application.status === 'pending'"
                  type="danger" 
                  size="small" 
                  @click="cancelApplication(application)"
                >
                  取消申请
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加入班级弹窗 -->
    <JoinClassDialog
      v-model:visible="showJoinDialog"
      @success="handleJoinSuccess"
    />


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  School, 
  Clock, 
  Reading, 
  Loading 
} from '@element-plus/icons-vue'
import JoinClassDialog from '@/components/JoinClassDialog.vue'
import { getStudentClasses, getStudentApplications, getUserClassId } from '@/api/class'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const showJoinDialog = ref(false)
const myClasses = ref([])
const applications = ref([])

// 统计数据
const stats = reactive({
  joinedClasses: 0,
  pendingApplications: 0,
  totalCourses: 0,
  purchasedCourses: 0,
  watchedCourses: 0,
  followedItems: 0
})

// 方法
const goHome = () => {
  window.location.href = '/home'
}

const loadMyClasses = async () => {
  loading.value = true
  try {
    // 首先获取用户的班级ID
    const userId = localStorage.getItem('userId') || '2' // 默认使用userId=2
    const classIdResponse = await getUserClassId(userId)
    
    if (classIdResponse.success && classIdResponse.data) {
      const classId = classIdResponse.data
      
      // 将获取到的班级ID存入localStorage
      localStorage.setItem('classId', classId)
      
      // 使用班级ID获取班级详细信息
      const url = `http://127.0.0.1:9001/user/class/info?classCode=${encodeURIComponent(classId)}`
      const res = await fetch(url, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('userToken') || ''}`
        }
      })
      const result = await res.json()
      
      if (result.code === 200 && result.data) {
        const d = result.data
        myClasses.value = [{
          id: d.id,
          className: d.name,
          grade: d.grade,
          classCode: d.classCode,
          teacherName: d.teacherName,
          studentCount: d.studentCount || 0,
          joinDate: d.createTime
        }]
        stats.joinedClasses = myClasses.value.length
        stats.totalCourses = myClasses.value.reduce((total, cls) => total + 8, 0)
      } else if (result.code === 400) {
        ElMessage.error('未加入班级')
        myClasses.value = []
        stats.joinedClasses = 0
        stats.totalCourses = 0
      }
    } else {
      // 获取班级ID失败，表示用户未加入班级
      ElMessage.error('未加入班级')
      myClasses.value = []
      stats.joinedClasses = 0
      stats.totalCourses = 0
    }
    
  } catch (error) {
    ElMessage.error('加载班级信息失败')
    myClasses.value = []
    stats.joinedClasses = 0
    stats.totalCourses = 0
  } finally {
    loading.value = false
  }
}

const loadApplications = async () => {
  try {
    // 使用API获取学生的申请记录
    // 这里假设当前学生ID为1，实际应该从用户认证信息中获取
    const currentStudentId = 1
    const response = await getStudentApplications(currentStudentId)
    console.log(response);
    if (response.success) {
      applications.value = response.data
      stats.pendingApplications = applications.value.filter(app => app.status === 'pending').length
    }
    // 模拟我购买/我观看课程数量
    stats.purchasedCourses = purchasedList.value.length
    stats.followedItems = followedList.value.length
  } catch (error) {
    ElMessage.error('加载申请记录失败')
  }
}

const handleJoinSuccess = (result) => {
  // 通过班级ID申请加入 - 只刷新申请记录
  if (result.incrementPending) {
    // 立即增加待审核申请数
    stats.pendingApplications += 1
  }
  loadApplications()
}

const viewClassDetail = (classItem) => {
  // 跳转到班级详情页面
  router.push(`/class/${classItem.id}`)
}

const leaveClass = async (classItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要退出班级 "${classItem.className}" 吗？退出后将无法访问该班级的学习内容。`,
      '确认退出',
      {
        confirmButtonText: '确定退出',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从列表中移除
    myClasses.value = myClasses.value.filter(cls => cls.id !== classItem.id)
    stats.joinedClasses = myClasses.value.length
    stats.totalCourses = myClasses.value.reduce((total, cls) => total + 8, 0)
    
    ElMessage.success('已成功退出班级')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出班级失败')
    }
  }
}

const cancelApplication = async (application) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消申请加入班级 "${application.className}" 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从列表中移除
    applications.value = applications.value.filter(app => app.id !== application.id)
    stats.pendingApplications = applications.value.filter(app => app.status === 'pending').length
    
    ElMessage.success('已取消申请')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消申请失败')
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const getApplicationStatusClass = (status) => {
  const statusMap = {
    pending: 'bg-yellow-100 text-yellow-800',
    approved: 'bg-green-100 text-green-800',
    rejected: 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

const getApplicationStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

const getFirstChar = (className) => {
  if (!className || typeof className !== 'string') return '班'
  const firstChar = className.charAt(0)
  return firstChar || '班'
}

// 我购买/我观看课程示例数据
const purchasedList = ref([
  { id: 101, title: 'Python数据分析 · 系列课', progress: 42, buyAt: '2025-05-12' },
  { id: 102, title: 'Vue3项目实战 · 系列课', progress: 10, buyAt: '2025-06-03' }
])
const followedList = ref([
  { id: 301, type: 'class', title: 'AI工程师直播班（2025秋）', dateRange: '2025-09 ~ 2025-12', followAt: '2025-10-10' },
  { id: 302, type: 'series', title: '前端工程化 · 系列课', progress: 30, followAt: '2025-10-12' }
])

const goToSeries = (course) => {
  // 演示跳转到系列页（此处假设 id 即为 courses/:id/series）
  const fakeId = 3 // 复用已有系列页示例
  window.location.href = `/courses/${fakeId}/series?type=series`
}

const goToFollowed = (item) => {
  if (item.type === 'class') {
    window.location.href = `/classes/${11}/intro?type=class`
  } else {
    goToSeries(item)
  }
}

// 监听班级列表刷新事件
const handleClassListRefresh = (event) => {
  console.log('🔄 收到班级列表刷新事件，重新加载班级信息')
  loadMyClasses()
}

// 生命周期
onMounted(() => {
  loadMyClasses()
  loadApplications()
  
  // 监听班级列表刷新事件
  window.addEventListener('classListRefreshed', handleClassListRefresh)
})

// 组件卸载时清理事件监听器
onBeforeUnmount(() => {
  window.removeEventListener('classListRefreshed', handleClassListRefresh)
})
</script>

<style scoped>
.logo-icon {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.logo-icon svg {
  width: 100%;
  height: 100%;
}
</style>
